package com.bwie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.pojo.TbUser;
import com.bwie.service.TbUserService;
import com.bwie.mapper.TbUserMapper;
import com.bwie.utils.R;
import com.bwie.vo.LoginVo;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author lenovo
 * @description 针对表【tb_user】的数据库操作Service实现
 * @createDate 2025-07-03 09:32:44
 */
@Service
public class TbUserServiceImpl extends ServiceImpl<TbUserMapper, TbUser>
        implements TbUserService {

    @Autowired
    TbUserMapper tbUserMapper;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public R login(LoginVo loginVo) {


        TbUser tbUser = tbUserMapper.selectOne(
                new QueryWrapper<TbUser>().lambda().eq(TbUser::getPhone, loginVo.getPhone())
        );
        if (tbUser == null) {
            return R.ERROR(500, "手机号不存在");
        }

        if (!loginVo.getPassword().equals(tbUser.getPassword())) {
            return R.ERROR(500, "密码错误");
        }


        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "123456").claim("userId", tbUser.getUserId())
                .claim("phone", tbUser.getPhone()).claim("realName", tbUser.getRealName()).compact();

        String tokenKey = "token-" + tbUser.getUserId();

        redisTemplate.opsForValue().set(tokenKey, token, 30, TimeUnit.MINUTES);


        tbUser.setToken(token);

        tbUser.setPassword(null);

        return R.OK(tbUser);
    }
}




